const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const jwt = require('jsonwebtoken')
const mysql = require('./mydbmysql')
const app = new Koa()
app.listen(9000, () => console.log('http://localhost:9000'))
app.use(bodyParser())
const db = mysql.createPool()

let secretKey = 'fewklfjlewkfjlewfjewljfwljfkewljflejflkewfjo;fewl;fjewwlfjfjew'

const router = new Router({prefix: '/api'})


// 中间件
app.use(async (ctx, next) => {
  let token = ctx.request.headers.token || ''
  if (['/api/login'].includes(ctx.request.path)) {
    await next()
  } else {
    if (!token) {
      ctx.body = {code: 1001, msg: '没有登录'}
    } else {
      let userinfo = jwt.verify(token, secretKey)
      // 对于解密后的信息进行数据查询，比对信息，正确则继续
      // 向下
      await next()
    }
  }
})

// 用户登录
router.post('/login', async ctx => {
  let {username, password} = ctx.request.body
  // 得到账号和密码查询数据是否有对应的账号和密码
  const sql = `select * from users where username='${username}' and password='${password}'`
  // 如果没有查询到则返回空数组，有数据则数据数据
  let ret = await db.query(sql)
  if (ret.length == 0) {
    // ctx.status = 200
    ctx.body = {code: 1000, msg: '登录账号和密码不正确'}
  } else {
    // 生成token
    let id = ret[0].id
    let token = jwt.sign({
      id,
      username,
      exp: Date.now() + 2 * 3600 * 1000
    }, secretKey)
    ctx.body = {
      code: 0, msg: 'ok', data: {
        id,
        username,
        nickname: '张三',
        token
      }
    }
  }
})


router.get('/users', async ctx => {
  let data = await db.query("select * from users")
  ctx.body = {
    code: 0,
    msg: 'ok',
    data
  }
})


app.use(router.routes())
